package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 定时关闭超时未支付的订单
     */
    //@Scheduled(cron = "0/30 * * * * ?") // 每隔30s执行一次
    public void cancelOrder(){
        // 1.查询符合条件（待支付，15分钟之前下单）的订单
        LocalDateTime beforeTime = LocalDateTime.now().minusSeconds(15);
        List<Orders> ordersList = orderMapper.selectByStatusAndLtTime(Orders.PENDING_PAYMENT,beforeTime);

        // 2.如果存在这样的订单，取消订单
        if (!CollectionUtils.isEmpty(ordersList)){
            ordersList.stream().forEach(orders -> {
                log.info("执行定时取消订单的操作,{}",orders.getId());
                // 取消订单
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("支付超时，系统自动取消");
                orderMapper.update(orders);
            });
        }

    }

    /**
     * 定时完成订单
     */
    //@Scheduled(cron = "0/30 * * * * ?") // 每隔30s执行一次
    public void completeOrder(){
        // 1.查询符合条件（待支付，15分钟之前下单）的订单
        LocalDateTime beforeTime = LocalDateTime.now().minusSeconds(5);
        List<Orders> ordersList = orderMapper.selectByStatusAndLtTime(Orders.DELIVERY_IN_PROGRESS,beforeTime);

        // 2.如果存在这样的订单，取消订单
        if (!CollectionUtils.isEmpty(ordersList)){
            ordersList.stream().forEach(orders -> {
                log.info("执行定时完成订单的操作,{}",orders.getId());
                // 完成订单
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }

    }

}
